package com.jason.campusinn.view;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;

import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.yuandian.wanna.R;
import com.yuandian.wanna.activity.navigationDrawer.OrderMeasureActivity;
import com.yuandian.wanna.utils.CommonMethodUtils;
import com.yuandian.wanna.wheelview.ArrayWheelAdapter;
import com.yuandian.wanna.wheelview.CityModel;
import com.yuandian.wanna.wheelview.DistrictModel;
import com.yuandian.wanna.wheelview.OnWheelChangedListener;
import com.yuandian.wanna.wheelview.ProvinceModel;
import com.yuandian.wanna.wheelview.WheelView;
import com.yuandian.wanna.wheelview.XmlParserHandler;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Created by yuandian on 2015/5/21.
 */
public class ProvincePopupWindow extends PopupWindow implements OnWheelChangedListener{

    private View view;
    private Activity context;
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;

    private Button btn_save;

    /**
     * 所有省
     */
    protected String[] mProvinceDatas;
    /**
     * key - 省 value - 市
     */
    protected Map<String, String[]> mCitisDatasMap = new HashMap<String, String[]>();
    /**
     * key - 市 values - 区
     */
    protected Map<String, String[]> mDistrictDatasMap = new HashMap<String, String[]>();

    /**
     * key - 区 values - 邮编
     */
    protected Map<String, String> mZipcodeDatasMap = new HashMap<String, String>();

    /**
     * 当前省的名称
     */
    protected String mCurrentProviceName;
    /**
     * 当前市的名称
     */
    protected String mCurrentCityName;
    /**
     * 当前区的名称
     */
    protected String mCurrentDistrictName ="";

    /**
     * 当前区的邮政编码
     */
    protected String mCurrentZipCode ="";

    /**
     * 解析省市区的XML数据
     */



    public ProvincePopupWindow(Activity context){

        this.context=context;

        //初始化页面
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.popup_choose_address, null);
        setContentView(view);
        btn_save=(Button)view.findViewById(R.id.provice_pop_btn);
        mViewCity=(WheelView)view.findViewById(R.id.id_city);
        mViewProvince=(WheelView)view.findViewById(R.id.id_province);
        mViewDistrict=(WheelView)view.findViewById(R.id.id_district);
        // 添加change事件
        mViewProvince.addChangingListener(this);
        // 添加change事件
        mViewCity.addChangingListener(this);
        // 添加change事件
        mViewDistrict.addChangingListener(this);
        setUpData();

        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OrderMeasureActivity.MY_PROVINCE = getmCurrentProviceName();
                OrderMeasureActivity.MY_CITY = getmCurrentCityName();
                OrderMeasureActivity.MY_DISTRICT = getmCurrentDistrictName();
                dismiss();
            }
        });

        // 设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        // 设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.popupStyle);
        // 实例化一个ColorDrawable颜色为半透明
//        ColorDrawable dw = new ColorDrawable(0xB0FFFFFF);
        // 设置SelectPicPopupWindow弹出窗体的背景
//        this.setBackgroundDrawable(dw);
        this.setOutsideTouchable(true);
        this.update();

    }

    public void setValue(String address)
    {
        LogUtils.d("address"+address);
        String addresses[] = address.split(" ");
        LogUtils.d("address "+ address + "address list size " + addresses.length );
        if(addresses.length < 0 )
            return;
        if(CommonMethodUtils.isEmpty(addresses[0]))
            return;
        int i=0, length = mProvinceDatas.length ;
        for(; i<length; i++)
        {
            if(addresses[0].equals(mProvinceDatas[i]))
                break;
        }
        if(i >= length)
            return;
        mViewProvince.setCurrentItem(i);
        mCurrentProviceName = addresses[0];
        updateCities();

        i=0;
        String areas[] =  mCitisDatasMap.get(addresses[0]);
        length = areas.length;
        for(; i< length; i++)
        {
            if(addresses[1].equals(areas[i]))
                break;
        }
        if(i >= length)
            return;
        mViewCity.setCurrentItem(i);
        mCurrentCityName = addresses[1];
        updateAreas();

        i=0;
        areas =  mDistrictDatasMap.get(addresses[1]);
        length = areas.length;
        for(; i< length; i++)
        {
            if(addresses[2].equals(areas[i]))
                break;
        }
        if(i >= length)
            return;
        mViewDistrict.setCurrentItem(i);
        mCurrentDistrictName = addresses[2];
        mCurrentZipCode = mZipcodeDatasMap.get(addresses[2]);
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {
            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
        }
    }


    private void setUpData() {
        initProvinceDatas();
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(context, mProvinceDatas));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
    }

    /**
     * 初始化控件地区信息
     */
    protected void initProvinceDatas()
    {
        List<ProvinceModel> provinceList = null;
        AssetManager asset = context.getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            //*/ 初始化默认选中的省、市、区
            if (provinceList!= null && !provinceList.isEmpty()) {
                mCurrentProviceName = provinceList.get(0).getName();
                List<CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList!= null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<DistrictModel> districtList = cityList.get(0).getDistrictList();
                    mCurrentDistrictName = districtList.get(0).getName();
                    mCurrentZipCode = districtList.get(0).getZipcode();
                }
            }
            //*/
            mProvinceDatas = new String[provinceList.size()];
            for (int i=0; i< provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinceDatas[i] = provinceList.get(i).getName();
                List<CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j=0; j< cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    DistrictModel[] distrinctArray = new DistrictModel[districtList.size()];
                    for (int k=0; k<districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        DistrictModel districtModel = new DistrictModel(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
                        mZipcodeDatasMap.put(districtList.get(k).getName(), districtList.get(k).getZipcode());
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictDatasMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisDatasMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {

        }
    }


    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
        String[] areas = mDistrictDatasMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[] { "" };
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<String>(context, areas));
        mViewDistrict.setCurrentItem(0);
        mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[0];
        mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities()
    {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProviceName = mProvinceDatas[pCurrent];
        String[] cities = mCitisDatasMap.get(mCurrentProviceName);
        if (cities == null) {
            cities = new String[] { "" };
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(context, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    public String getSelectedResult()
    {
        return mCurrentProviceName +" "+mCurrentCityName+" "
                +mCurrentDistrictName;
    }

    public String getmCurrentZipCode() {
        return mCurrentZipCode;
    }

    public void setmCurrentZipCode(String mCurrentZipCode) {
        this.mCurrentZipCode = mCurrentZipCode;
    }

    public String getmCurrentDistrictName() {
        return mCurrentDistrictName;
    }

    public void setmCurrentDistrictName(String mCurrentDistrictName) {
        this.mCurrentDistrictName = mCurrentDistrictName;
    }

    public String getmCurrentCityName() {
        return mCurrentCityName;
    }

    public void setmCurrentCityName(String mCurrentCityName) {
        this.mCurrentCityName = mCurrentCityName;
    }

    public String getmCurrentProviceName() {
        return mCurrentProviceName;
    }

    public void setmCurrentProviceName(String mCurrentProviceName) {
        this.mCurrentProviceName = mCurrentProviceName;
    }
}
